const router = require('express').Router();
const { dbQuery, dbError, updateToken, sqlStrQuotationHandle } = require('../../tools');
const fs = require('fs');
const pathLib = require('path');
const vertoken = require('../../token');

router.get('/name', function(req, res) {
	const {id, name} = req.query;
	const nameStr = sqlStrQuotationHandle(name);
	dbQuery(`update user_table set name='${nameStr}' where id='${id}'`)
	.then(() => {
		dbQuery(`select id,account,name,gender,introduction,avator from user_table where id='${id}'`)
		.then(data => {
			vertoken.setToken(data[0]).then(token => {
				res.send({code: 1,message: '修改成功', data: data[0], token});
			});
		});
	})
	.catch(err => {
		dbError(res, err, '修改名称失败');
	});
});
router.get('/intro', function(req, res) {
	const {id, introduction} = req.query;
	const introductionStr = sqlStrQuotationHandle(introduction);
	dbQuery(`update user_table set introduction='${introductionStr}' where id='${id}'`)
	.then(() => {
		dbQuery(`select id,account,name,gender,introduction,avator from user_table where id='${id}'`)
		.then(data => {
			vertoken.setToken(data[0]).then(token => {
				res.send({code: 1,message: '修改成功', data: data[0], token});
			});
		});
	})
	.catch(err => {
		dbError(res, err, '修改简介失败');
	});
});
router.get('/gender', function(req, res) {
	const {id, gender} = req.query;
	dbQuery(`update user_table set gender='${gender}' where id='${id}'`)
	.then(() => {
		dbQuery(`select id,account,name,gender,introduction,avator from user_table where id='${id}'`)
		.then(data => {
			vertoken.setToken(data[0]).then(token => {
				res.send({code: 1,message: '修改成功', data: data[0], token});
			});
		});
	})
	.catch(err => {
		dbError(res, err, '修改性别失败');
	});
});
router.post('/avator', function(req, res) {
	if (!req.files || req.files.length < 1) {
		res.send({code: 0, message: '无上传文件'});
		return;
	}
	const {id} = req.body;
	const file = req.files[0];
	const avatorFolder = 'img/user_avator/'

	// 修改头像路径
	const finalAvatorUrl = `${file.destination}/${avatorFolder}${file.filename}${pathLib.parse(file.originalname).ext}`;
	new Promise((resolve, reject) => {
		// 修改上传文件名
		fs.rename(
			file.path,
			finalAvatorUrl,
			function(err) {
				if (err) {
					console.log(err);
					reject(err);
				}
				resolve();
			}
		);
	})
	.then(() => {
		let originAvatorDel = () => new Promise((resolve, reject) => {
			// 删除原头像
			dbQuery(`select avator from user_table where id='${id}'`)
			.then(data => {
				const imgUrl = data[0].avator;
				if (imgUrl === `${avatorFolder}person_300.png`) {
					return resolve('默认头像不删除');
				}
				fs.unlink(`./static/${imgUrl}`, function(err) {
					if (err) {
						reject(err);
					}
					resolve('原头像删除完成');
				});
			})
			.catch(err => {
				dbError(res, err);
				reject(err);
			});
		});
		let updateSQL = () => new Promise((resolve, reject) => {
			// 更新数据库头像路径
			dbQuery(`update user_table set avator='${finalAvatorUrl.split('./static/')[1]}' where id='${id}'`)
			.then(() => {
				resolve('数据库更新完成');
			})
			.catch(() => {
				reject('数据库更新错误')
			});
		});
		// 删除原头像,更改数据库数据,都完成后发送res
		originAvatorDel().then(() => updateSQL())
		.then(() => {
			updateToken(res, undefined, id, {code: 1, message: '更新完成'});
		})
		.catch(err => {
			dbError(res, err);
		});
	})
	.catch(err => {
		console.log(err, file.path);
		// 修改上传文件路径失败,删除临时文件
		fs.unlink(file.path, function(err) {
			if (err) {
				console.log('上传临时文件删除失败');
			}
		});
		res.send({code: 0, message: '数据库错误'});
		return;
	});
});

module.exports = router;
